<template>
  <div class="app-container">
    <el-form ref="dataForm" :model="Form" :rules="FormRules" label-width="80px" class="form-container">
      <el-card>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="Form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="isPublic">
              <el-select v-model="Form.isPublic" class="filter-item" placeholder="请选择类型">
                <el-option v-for="item in TypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 测点标号 -->
        <el-row>
          <el-col :span="11">
            <el-form-item prop="picData">
              <el-upload
                class="avatar-uploader"
                :action="imgUploadUrl"
                :headers="httpHeaders"
                :data="Data"
                :auto-upload="true"
                :show-file-list="false"
                :on-change="handleCreateImgChange"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                 <div slot="tip" class="el-upload__tip">测点分布图<span>（只能上传jpg/png文件）</span>  </div>
              </el-upload>
              
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-row>
              <el-col :span="4" v-for="(item,i) in codeList" :key="i">
                <el-tag class="tag" closable :disable-transitions="false" @close="handleClose(i)">{{item}}</el-tag>
              </el-col>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="codeName"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              ></el-input>
              <el-button v-else class="button-new-tag" type="primary" size="small" @click="showInput">添加测点标号</el-button>
            </el-row>
          </el-col>
        </el-row>
        <!-- 标号对应区域位置关系表 -->
        <div class="tit">
          <span>标号对应区域位置关系表</span>
        </div>
        <el-table :data="zonePositionList" border highlight-current-row v-loading="loading" class="tb-edit">
          <el-table-column type="index" min-width="30"></el-table-column>
          <el-table-column prop="name" label="分析区域" width="120">
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="analysisMethodId" label="分析方法" width="130">
            <template slot-scope="scope">
              <span v-if="scope.row.analysisMethodId == 1">不分析</span>
              <span v-else>局部稳态分析</span>
            </template>
          </el-table-column>
          <el-table-column prop="analysisMethodId" label="是否分层" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.level >0">分层</span>
              <span v-else>不分层</span>
            </template>
          </el-table-column>
          <el-table-column label="标号对应区域位置">
            <template slot-scope="scope">
              <div class="level">
                <span>上层：{{scope.row.code1}}</span>
                <span v-if="scope.row.level==1">中层：{{scope.row.code2}}</span>
                <span v-if="scope.row.level==1">下层：{{scope.row.code3}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-col :span="24" :style="{padding:'15px',textAlign:'right'}">
          <el-button type="success" size="small" @click="handleCreate()">
            <span>新增测点位置关系</span>
          </el-button>
        </el-col>
        <el-col :span="24" :style="{padding:'15px',textAlign:'center'}">
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-col>
      </el-card>
    </el-form>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-width="180px" :model="zoneForm" :rules="zoneFormRules" ref="zoneForm">
        <el-form-item label="模板名称" prop="name" width="100%">
          <el-input v-model="zoneForm.name"></el-input>
        </el-form-item>
        <el-form-item label="分析方法" prop="analysisMethodId">
          <el-select v-model="zoneForm.analysisMethodId" class="filter-item" placeholder="请选择分析方法">
            <el-option v-for="item in analysisMethodOptions" :key="item.analysisMethodId" :label="item.label" :value="item.analysisMethodId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分层方式" prop="level">
          <el-select v-model="zoneForm.level" class="filter-item" placeholder="请选择分析方法">
            <el-option v-for="item in levelOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="zoneForm.level==1?'上层标号对应区域位置':'标号对应区域位置'" prop="code1">
          <el-select v-model="zoneForm.code1" class="filter-item" placeholder="请选择标号对应区域位置" @change="code1Filter">
            <el-option v-for="item in codeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
          </el-select>
        </el-form-item>
        <el-form-item label="中层标号对应区域位置" v-if="zoneForm.level==1" prop="code2">
          <el-select v-model="zoneForm.code2" class="filter-item" placeholder="请选择标号对应区域位置" @change="code2Filter">
            <el-option v-for="item in codeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
          </el-select>
        </el-form-item>
        <el-form-item label="下层标号对应区域位置" v-if="zoneForm.level==1" prop="code3">
          <el-select v-model="zoneForm.code3" class="filter-item" placeholder="请选择标号对应区域位置" @change="code3Filter">
            <el-option v-for="item in codeOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dialogConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getDistributionData, updateDistribution } from "@/api/distribution";
import { getSensorList } from "@/api/position";
import { getAnalysisMethodList } from "@/api/analysisMethod";
import {
  getZonePositionList,
  updateZonePosition,
  createZonePosition,
  deleteZonePosition
} from "@/api/zonePosition";
import UploadImg from "@/components/Upload/UploadImg";
import trackVue from "../../tasks/components/track.vue";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
export default {
  components: { UploadImg },
  props: {
    deviceType: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      httpHeaders: {
        Authorization: getToken()
      },
      TypeOptions: [{ value: 1, label: "公有" }, { value: 0, label: "私有" }],
      levelOption: [{ value: 1, label: "分层" }, { value: 0, label: "不分层" }],
      textMap: {
        createCarZone: "新增冷藏车标号对应区域位置关系",
        createWarehouseZone: "新增库房标号对应区域位置关系",
        updateCarZone: "编辑冷藏车标号对应区域位置关系",
        updateWarehouseZone: "编辑冷藏车标号对应区域位置关系"
      },
      dialogStatus: "",
      dialogFormVisible: false,
      Form: {
        name: "",
        isPublic: null,
        picData: null
      },
      FormRules: {
        name: [
          { required: true, message: "请输入布点方式名称", trigger: "blur" }
        ],
        isPublic: [
          { required: true, message: "请选择类型", trigger: "change" }
        ],
        picData: [
          { required: true, message: "请上传标点图片", trigger: "change" }
        ]
      },
      imgUploadUrl: "http://gsp.coldcloud.com/distribution/pic/update",
      imageUrl: "",
      Data: {},
      loading: false,
      codeList: [],
      codeOptions: [],
      zonePositionList: [],
      analysisMethodOptions: [],
      distributionOptions: [],
      inputVisible: false,
      codeName: "",
      Form: {
        name: "",
        type: "",
        isPublic: null,
        picData: ""
      },
      FormRule: {},
      zoneForm: {
        zoneId: null,
        name: "",
        analysisMethodId: null,
        level: null,
        code1: null,
        code2: null,
        code3: null
      },
      zoneFormRules: {
        name: [{ required: true, message: "请输入分析区域", trigger: "blur" }],
        analysisMethodId: [
          { required: true, message: "请选择分析方法", trigger: "change" }
        ],
        level: [
          { required: true, message: "请选择分层方式", trigger: "change" }
        ],
        code1: [
          { required: true, message: "请选择对应标号方式", trigger: "change" }
        ],
        code2: [
          { required: true, message: "请选择对应标号方式", trigger: "change" }
        ],
        code3: [
          { required: true, message: "请选择对应标号方式", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["customerid"])
  },

  watch: {
    Form: {
      handler(newval, oldval) {
        this.Form.picData = newval.pic;
      },
      deep: true,
      immediate: true
    }
  },

  methods: {
    //上传图片成功
    handleAvatarSuccess() {
      this.$message({
        message: "图片上传成功",
        type: "success"
      });
      this.getData();
    },
    // 新增时图片上传前检查
    handleCreateImgChange(file, fileList) {
      // console.log(file, fileList)
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
        fileList.pop();
      } else {
        this.Form.picData = file;
        this.imageUrl = file.url;
      } 
      return isImage;
    },

    // 删除测点标号
    handleClose(tag) {
      this.codeList.splice(this.codeList.indexOf(tag), 1);
      this.codeOptions = this.codeList.map((v, i) => {
            return { value: v, label: v, disabled: false };
          });

    },

    showInput() {
      this.inputVisible = true;
      let self = this;
      this.$nextTick(_ => {
        self.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 新增测点标号
    handleInputConfirm() {
      let codeName = this.codeName;
      if (codeName) {
        if (this.codeList.indexOf(codeName) == -1) {
          this.codeList.push(codeName);
          this.codeOptions = this.codeList.map((v, i) => {
            return { value: v, label: v, disabled: false };
          });
        } else {
          this.$message({
            message: "已有相同标号的测点",
            type: "warning"
          });
        }
      }
      this.inputVisible = false;
      this.codeName = "";
    },

    //获取标号对应区域位置关系表
    getZonePosition() {
      this.loading = true;
      getZonePositionList({ distributionId: this.$route.params.id })
        .then(res => {
          this.zonePositionList = res.data;
          this.loading = false;
        })
        .catch(e => {});
    },

    //获取位置列表
    getposition() {
      getSensorList({ distributionId: this.$route.params.id }).then(res => {
        this.codeList = res.data.map(p => p.code);
        this.codeOptions = this.codeList.map((v, i) => {
          return { value: v, label: v, disabled: false };
        });
      });
    },

    //获取布点方式基本信息
    getData() {
      getDistributionData({ id: this.$route.params.id }).then(res => {
        this.Form = res.data;
        this.Data = { id: res.data.id };
        if(res.data.pic){
          this.imageUrl = res.data.pic.url;
        } else {
          this.imageUrl = ''
        }
        
      });
    },

    //获取分析方法
    getAnalysisMethod() {
      getAnalysisMethodList().then(res => {
        this.analysisMethodOptions = res.data.map(value => {
          return { analysisMethodId: value.mid, label: value.label };
        });
      });
    },

    // 选中的设为禁用
    code1Filter(val) {
      this.codeOptions.forEach(v => {
        if (val == v.value) {
          v.disabled = !v.disabled;
        }
      });
    },

    code2Filter(val) {
      this.codeOptions.forEach(v => {
        if (val == v.value) {
          v.disabled = !v.disabled;
        }
      });
    },
    code3Filter(val) {
      this.codeOptions.forEach(v => {
        if (val == v.value) {
          v.disabled = !v.disabled;
        }
      });
    },

    //重置form
    resetForm() {
      this.zoneForm = {
        zoneId: null,
        name: "",
        analysisMethodId: null,
        level: null,
        code1: null,
        code2: null,
        code3: null
      };
    },

    handleEdit(index, row) {
      this.zoneForm = Object.assign(this.zoneForm, row);
      this.codeOptions.forEach(sensor => {
        this.zonePositionList.map(s => {
          if(s.zoneId != row.zoneId && ( sensor.label == s.code1 ||
            sensor.label == s.code2 ||
            sensor.label == s.code3)){
              return ( sensor.disabled = true)
          }
          
        });
      });
      this.deviceType === 2
        ? (this.dialogStatus = "updateCarZone")
        : (this.dialogStatus = "updateWarehouseZone");
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.zoneForm.clearValidate();
      });
    },

    // 新增位置关系表弹窗
    handleCreate() {
      this.resetForm();
      this.codeOptions.forEach(sensor => {
        this.zonePositionList.map(s => {
          if (
            sensor.label == s.code1 ||
            sensor.label == s.code2 ||
            sensor.label == s.code3
          ) {
            return (sensor.disabled = true);
          }
        });
      });
      this.deviceType === 2
        ? (this.dialogStatus = "createCarZone")
        : (this.dialogStatus = "createWarehouseZone");
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.zoneForm.clearValidate();
      });
    },

    dialogConfirm() {
      if (
        this.dialogStatus == "createCarZone" ||
        this.dialogStatus == "createWarehouseZone"
      ) {
        this.ZoneCreate();
      } else {
        this.ZoneUpdate();
      }
    },

    // 修改标号对应区域位置
    ZoneUpdate() {
      this.$refs["zoneForm"].validate(valid => {
        if (valid) {
          let tempData = Object.assign({}, this.zoneForm, {
            distributionId: this.$route.params.id
          });
          updateZonePosition(tempData).then(res => {
            this.$notify({
              title: "成功",
              message: "修改标号对应区域位置成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getZonePosition();
          });
        }
      });
    },
    
// tijiao
    onSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          let tempData = Object.assign({}, this.Form);
          updateDistribution(tempData).then(_ => {
            this.$notify({
              title: "成功",
              message: "修改布点信息成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    // 新增关系
    ZoneCreate() {
      this.$refs["zoneForm"].validate(valid => {
        if (valid) {
          createZonePosition(
            Object.assign({}, this.zoneForm, {
              distributionId: this.$route.params.id
            })
          ).then(res => {
            this.$notify({
              title: "成功",
              message: "新增标号对应区域位置成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getZonePosition();
          });
        }
      });
    },

    // 删除关系
    handleDel(index, row) {
      this.$confirm("确认删除该数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading = true;
          deleteZonePosition(row).then(() => {
            this.loading = false;
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            this.getZonePosition();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
  },
  mounted() {
    this.getData();
    this.getZonePosition();
    this.getAnalysisMethod();
    this.getposition();
  }
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height:300px;
  line-height:300px;
  text-align: center;
}
.avatar {
  width: 300px;
  height:300px;
  display: block;
  border: 1px solid #eee;
  padding: 2px;
  box-shadow: 0 6px 18px 0 rgba(232, 237, 250, 0.5);
}
.el-upload__tip {
    font-size: 14px;
    color: #606266;
    text-align: center;
    span{
      font-size: 12px;
    }
}

.tag {
  margin-bottom: 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.tit {
  text-align: center;
  font-size: 18px;
  font-weight: 700;
  padding: 15px;
}
.level {
  span {
    display: inline-block;
    margin-right: 15px;
  }
}
</style>
